package com.xiaoquan.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.xiaoquan.common.to.es.SkuEsModel;
import com.xiaoquan.gulimall.search.config.GulimallElasticSearchConfig;
import com.xiaoquan.gulimall.search.constant.EsConstant;
import com.xiaoquan.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @authro dxq
 * @date 2021年06月21日 21:00
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    /**
     * 上架商品 保存到es中
     * @param skuEsModels
     */
    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 1、给es中建立索引。product  建立好映射关系

        // BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            // 1、构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX); // 指定索引添加
            indexRequest.id(model.getSkuId().toString()); // 为每一个商品都添加唯一的Id
            String s = JSON.toJSONString(model);
            indexRequest.source(s, XContentType.JSON); // 指定数据 和 内容类型 JSON

            bulkRequest.add(indexRequest); // 将每个保存请求 让如bulk 中 批量 保存
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);

        // TODO 如果es批量保存出现了错误
        boolean b = bulk.hasFailures();// 判断是否是否拥有错误  true是有错误 false就是没错误
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架完成：{}",collect );
        return b;
    }
}
